<template>
  <div class="topic-search">
    <el-select
      v-model="selectedTopics"
      multiple
      filterable
      remote
      reserve-keyword
      placeholder="搜索话题..."
      :remote-method="handleSearch"
      :loading="loading"
      :multiple-limit="maxSelection"
      class="topic-select"
      @change="handleChange"
    >
      <el-option
        v-for="topic in searchResults"
        :key="topic.id"
        :label="topic.name"
        :value="topic.id"
        class="topic-option"
      >
        <div class="topic-option-content">
          <el-avatar
            :size="24"
            :src="getMediaUrl(topic.avatar)"
            class="topic-avatar"
          >
            {{ topic.name?.charAt(0) }}
          </el-avatar>
          <div class="topic-info">
            <span class="topic-name">{{ topic.name }}</span>
            <span class="topic-stats">
              {{ formatCount(topic.followerCount || 0) }} Follow
            </span>
          </div>
        </div>
      </el-option>
    </el-select>

    <!-- 已选择的话题标签 -->
    <div class="selected-topics" v-if="selectedTopicList.length > 0">
      <el-tag
        v-for="topic in selectedTopicList"
        :key="topic.id"
        closable
        type="primary"
        class="topic-tag"
        @close="handleRemoveTopic(topic.id)"
      >
        {{ topic.name }}
      </el-tag>
    </div>
  </div>
</template>

<script setup>
import {computed, ref, watch} from 'vue'
import {debounce} from 'lodash-es'
import {searchTopics} from '@/api/topic'
import {getMediaUrl} from '@/utils/media'
import {formatCount} from '@/utils/format'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  maxSelection: {
    type: Number,
    default: 5
  },
  placeholder: {
    type: String,
    default: '搜索话题...'
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const selectedTopics = ref([])
const searchResults = ref([])
const loading = ref(false)
const topicMap = ref(new Map()) // 存储话题ID到话题对象的映射

// 计算已选择的话题列表
const selectedTopicList = computed(() => {
  return selectedTopics.value.map(id => topicMap.value.get(id)).filter(Boolean)
})

// 监听外部传入的值变化
watch(() => props.modelValue, (newValue) => {
  if (Array.isArray(newValue)) {
    selectedTopics.value = [...newValue]
  }
}, { immediate: true })

// 搜索话题的防抖函数
const handleSearch = debounce(async (query) => {
  if (!query || query.trim().length < 1) {
    searchResults.value = []
    return
  }

  loading.value = true
  try {
    const response = await searchTopics({
      keyword: query.trim(),
      limit: 20
    })
    
    if (response.code === 200) {
      searchResults.value = response.data || []
      
      // 更新话题映射
      searchResults.value.forEach(topic => {
        topicMap.value.set(topic.id, topic)
      })
    } else {
      searchResults.value = []
    }
  } catch (error) {
    console.error('搜索话题失败:', error)
    searchResults.value = []
  } finally {
    loading.value = false
  }
}, 300)

// 处理选择变化
const handleChange = (value) => {
  selectedTopics.value = value
  emit('update:modelValue', value)
  emit('change', {
    topicIds: value,
    topics: selectedTopicList.value
  })
}

// 移除话题
const handleRemoveTopic = (topicId) => {
  const index = selectedTopics.value.indexOf(topicId)
  if (index > -1) {
    selectedTopics.value.splice(index, 1)
    handleChange(selectedTopics.value)
  }
}

// 清空选择
const clearSelection = () => {
  selectedTopics.value = []
  handleChange([])
}

// 暴露方法给父组件
defineExpose({
  clearSelection
})
</script>

<style lang="scss" scoped>
.topic-search {
  .topic-select {
    width: 100%;
    
    :deep(.el-select__tags) {
      max-height: 80px;
      overflow-y: auto;
    }
  }
  
  .selected-topics {
    margin-top: 12px;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    
    .topic-tag {
      margin: 0;
    }
  }
}

.topic-option-content {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
  
  .topic-avatar {
    flex-shrink: 0;
    background: linear-gradient(135deg, $primary-color, #40a9ff);
    color: white;
    font-weight: 600;
    font-size: 12px;
  }
  
  .topic-info {
    flex: 1;
    min-width: 0;
    
    .topic-name {
      display: block;
      font-weight: 500;
      color: $text-color;
      @include text-ellipsis;
    }
    
    .topic-stats {
      display: block;
      font-size: 12px;
      color: $text-tertiary;
      margin-top: 2px;
    }
  }
}

// 自定义下拉选项样式
:deep(.el-select-dropdown__item) {
  height: auto;
  padding: 8px 12px;
  
  &.hover {
    background-color: $background-light;
  }
}
</style>
